<template>
	<view class="container">
		<navigationBar :titleName="'微信登录'"></navigationBar>
		<u-toast ref="uToast"></u-toast>
		<view class="content">
			<view class="login">
				<block v-if="canIUse">
					<view class="title" style="margin-top: 30rpx;">
						才能网旗下产品-才能招标
					</view>
					<view class="title">
						 
						全面、精准、便捷的招投标信息查询平台
						 
					</view>
					<view class="photo">
						<image src="/static/images/logo/logo.png" class="avatar"></image>
					</view>
					<view class="auth" v-if="!phoneAuth">
						<button class="button" type="primary" open-type="getUserInfo"
							@getuserinfo="bindGetuserInfo">使用微信账号登录</button>
						<navigator v-if="!hasAuth" class="btn-cancel" url="/pages/index/index/index"
							open-type="switchTab">取消
						</navigator>
					</view>
					<view v-if="phoneAuth" style="text-align: center;">
						<uni-icons type="arrowthindown"></uni-icons>
						<text style="font-size: 26rpx;">获取手机号，请点击【微信快速登录】</text>
						<uni-icons type="arrowthindown"></uni-icons>
						<button class="btn row_c" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
							<uni-icons type="weixin" color="#2ccb67"></uni-icons>微信快速登录
						</button>
						<!-- <button class="btn row_c" open-type='getUserInfo' @getuserinfo="getuserinfo">微信账号登录</button> -->
					</view>
				</block>
				<block v-else>
					<view class="upgrade">当前微信版本太低不支持该小程序部分功能，请升级微信版本</view>
				</block>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex';
	import api from '@/config/baseUrl.js';
	export default {
		data() {
			return {
				hasAuth: true,
				canIUse: true,
				// 用户未进行过手机号授权
				phoneAuth: false,
				phoneUse: null
			};
		},
		onLoad() {
			
			let isLogin = uni.getStorageSync('isLogin') ;
			if(isLogin==1){
				return ;
			}
			
			
			// 判断应用的 API，回调，参数，组件等是否在当前版本可用
			this.canIUse = uni.canIUse('button.open-type.getUserInfo');
			/*是否授权*/
			uni.getSetting({
				success: res => {
					console.log("res.authSetting['scope.userInfo']",res.authSetting['scope.userInfo'])
					/*已经授权直接登录  */
					if (res.authSetting['scope.userInfo']) {
						this.wechatAppLogin(true); //登录
						// 不出现手机号授权按钮 ，直接进入到首页
						this.phoneAuth = false
						// 已授权 直接登陆
						this.$refs.uToast.show({
							message:"您已进行过授权，直接登录",
							type: 'success'
						})	
						 
						
					} else {
						// 授权失败直接导航至首页
						this.hasAuth = false;
					}
				}
			});
		},
		methods: {
			...mapMutations(['login']),  
			/*微信小程序登录*/
			wechatAppLogin(isBack = false) {
				let this_ = this ;
				// console.log("opooooooooooooooooooo")
				/*登录提示*/
				// uni.showLoading({
				// 	title: "正在登录",
				// 	mask: true
				// }); 
				/*微信登录*/
				uni.login({
					provider: 'weixin',
					success: loginResult => {
						// 存储到缓存，获取到手机号之后再使用
						let code = loginResult.code;
						
						/*获取用户信息*/
						uni.getUserInfo({
							success: result => {
								/*获取分享id*/
								let share_user_id = uni.getStorageSync('share_user_id');
								share_user_id = share_user_id > 0 ? share_user_id : 0;
								// console.info("===============微信登录"+share_user_id)
								console.info(result)
								// 将result转化为字符串存贮到缓存  留到获取手机号使用
								let weChatResult=JSON.stringify(result)
								
								uni.setStorageSync('weChatResult', weChatResult);
								/*登录验证*/
								this.$app.request({
									url: api.api.wechat.miniAppLogin,
									data: {
										share_user_id: share_user_id,
										code: code,
										rawData: result.rawData,
										encryptedData: result.encryptedData,
										iv: result.iv,
										signature: result.signature
									},
									method: 'POST',
									dataType: 'json',
									success: res => {
										console.log("===============微信登录res",res)
										
										if (res.code == 200) {
											
											
											/*更新登录状态,保存用户数据*/
											//如果已经绑定手机号码，则直接登录
											if(res.msg=='notPhone'){
												//res.data 里面存的是unionid
												uni.setStorageSync('unionid', res.data);
												//否则要求用户绑定手机号码
												uni.reLaunch({
													url: `/pagesUser/bindMailbox?status=1&page=3`
												});
												
											}else{
												this_.login(res.data);
												uni.reLaunch({
													url: '/pages/index/index'
												});
											}
											
											
										} else {
											alert(res.msg, 'warning');
										}
									}
								});
							},
							fail: result => {
								uni.showModal({
									content: '很抱歉，手机号授权失败了，请重新进行登录授权操作',
									success: function (res) {
										if (res.confirm) {
											console.log('用户点击确定');
											uni.reLaunch({
												url:'/pagesCommon/miniAppLogin'
											})
										} else if (res.cancel) {
											console.log('用户点击取消');
										}
									}
								});
								uni.hideLoading();
							}
						});
					}
				});
			},
			
			
			bindGetuserInfo() {

				this.wechatAppLogin(true); //登录
				this.phoneAuth = true

			},
			//微信小程序登录
			getPhoneNumber(e) {
				// console.log("111111onGetPhoneNumber", e);


				if (e.detail.errMsg == 'getPhoneNumber:ok') {
					uni.showLoading({
						title: "正在登录,请稍候...."
					});
					// 拿取unionid
					let unionid = uni.getStorageSync('unionid')

					// 拿取微信授权时存储的信息result
					let result = uni.getStorageSync('weChatResult')

					if (result) {
						result = JSON.parse(result)
					}
					// console.log("result", result)
					let data = {
						rawData: result.rawData,
						encryptedData: e.detail.encryptedData,
						iv: e.detail.iv,
						signature: result.signature,
						unionId: unionid
					}

					this.$app.request({
						url: this.$baseApp.api.wechat.miniPhone,
						data: data,
						method: 'POST',
						dataType: 'json',
						success: res => {
							if (res.code == 200) {
								// 将返回的信息都保存到本地中
								let userMsg = res.data
								userMsg = JSON.stringify(userMsg)
								uni.setStorageSync('userInfo', userMsg);
							
								
								// console.log("授权完成",userMsg)
								// 页面跳转至首页
								this.toIndex()
							} else {
								this.$alert(res.msg);
							}
						},
						fail: err => {
							// this.$alert(err.msg);
							// 失败了 清除所有缓存退出小程序
							uni.clearStorage();
							uni.showModal({
								content: '很抱歉，手机号授权失败了，请重新进行登录授权操作',
								success: function (res) {
									if (res.confirm) {
										console.log('用户点击确定');
										uni.reLaunch({
											url:'/pagesCommon/miniAppLogin'
										})
									} else if (res.cancel) {
										console.log('用户点击取消');
									}
								}
							});

							
						},
						complete: res => {
							
							/*隐藏加载框*/
							uni.hideLoading();
						}
					});
					setTimeout(function() {
						uni.hideLoading();
					}, 2000);

				}


			},
			// 跳转至登录页面
			toIndex() {

				uni.reLaunch({
					url: '/pages/index/index'
				});
				setTimeout(() => {

					uni.$emit('dataFlash')

				}, 3000)
			}
		}
	};
</script>

<style lang="scss" scoped>
	.login {
		view {
			padding: 50rpx;
			text-align: center;
			.title{
				text-align: center;
				font-size: 36rpx;
				
			}
			image {
				width: 250rpx;
				height: 250rpx;
			}
		}

		.auth {
			.btn-cancel {
				margin-top: 20rpx;
				border-radius: 100px;
				font-size: 32rpx;
				color: #999;
			}
		}

		.upgrade {
			font-size: 30rpx;
		}
	}

	button::after {
		border: 0;
	}
</style>
